<template>
  <div class="chat-window">
    <!-- 消息列表 -->
    <div class="messages" ref="messageContainer">
      <div v-for="message in messages" :key="message.id" class="message">
        <!-- Basic message display - enhance later -->
        <span>{{ message.senderId }}: {{ message.content }} ({{ formatTimestamp(message.timestamp) }})</span>
      </div>
    </div>
    <!-- 输入框 -->
    <div class="input-box">
      <input type="text" v-model="newMessage" @keyup.enter="handleSendMessage" placeholder="输入消息...">
      <button @click="handleSendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue';
import { useMessage } from '@/composables/chat/useMessage';
import { useSocket } from '@/composables/chat/useSocket'; // Import useSocket for cleanup

// Define props to accept roomId
const props = defineProps<{ roomId: string }>();

const { messages, sendMessage, fetchMessages } = useMessage(props.roomId);
const { off } = useSocket(); // Get 'off' for cleanup
const newMessage = ref('');
const messageContainer = ref<HTMLElement | null>(null);

const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

const handleSendMessage = () => {
  if (newMessage.value.trim()) {
    sendMessage(newMessage.value);
    newMessage.value = '';
    scrollToBottom(); // Scroll down after sending
  }
};

// Format timestamp (basic example)
const formatTimestamp = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString();
};

// Watch for new messages and scroll down
watch(messages, () => {
  scrollToBottom();
}, { deep: true });

// Fetch initial messages when component mounts
onMounted(() => {
  // fetchMessages(); // fetchMessages is now called within useMessage when socket connects
  scrollToBottom(); // Scroll down initially
});

// Clean up socket listener when component unmounts
onUnmounted(() => {
  console.log(`ChatWindow for room ${props.roomId} unmounted, cleaning up listeners.`);
  // Remove the specific listener added in useMessage
  off('chat_message');
  // Optionally leave the room on the server if needed
  // emit('leave_room', { roomId: props.roomId });
});

</script>
<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.message {
  margin-bottom: 8px;
  padding: 5px 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  /* Add styles for sender vs receiver later */
}
.input-box {
  display: flex;
  padding: 10px;
  border-top: 1px solid #eee;
}

.input-box input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
}

.input-box button {
  padding: 8px 15px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.input-box button:hover {
  background-color: #0056b3;
}
</style>